package com.trace.demo.controller;

import com.trace.demo.entity.FarmingActivity;
import com.trace.demo.entity.FarmingInfo;
import com.trace.demo.entity.User;
import com.trace.demo.repository.FarmingActivityRepository;
import com.trace.demo.repository.FarmingInfoRepository;
import com.trace.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.HashMap;

/**
 * 种植信息控制器
 */
@RestController
@RequestMapping("/farming-info")
public class FarmingInfoController {

    private final FarmingInfoRepository farmingInfoRepository;
    private final UserRepository userRepository;
    private final FarmingActivityRepository farmingActivityRepository;

    @Autowired
    public FarmingInfoController(
            FarmingInfoRepository farmingInfoRepository,
            UserRepository userRepository,
            FarmingActivityRepository farmingActivityRepository) {
        this.farmingInfoRepository = farmingInfoRepository;
        this.userRepository = userRepository;
        this.farmingActivityRepository = farmingActivityRepository;
    }

    /**
     * 保存种植信息
     * @param userId 用户ID
     * @param farmingInfo 种植信息
     * @return 保存的种植信息
     */
    @PostMapping("/user/{userId}")
    @Transactional
    public ResponseEntity<?> saveFarmingInfo(
            @PathVariable Long userId,
            @RequestBody FarmingInfo farmingInfo) {
        try {
            return userRepository.findById(userId)
                    .map(user -> {
                        farmingInfo.setUser(user);

                        // 生成批次ID，如果没有提供
                        if (farmingInfo.getBatchId() == null || farmingInfo.getBatchId().isEmpty()) {
                            String batchId = "FARM-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
                            farmingInfo.setBatchId(batchId);
                        }

                        // 设置创建和更新时间
                        if (farmingInfo.getCreatedAt() == null) {
                            farmingInfo.setCreatedAt(LocalDateTime.now());
                        }
                        farmingInfo.setUpdatedAt(LocalDateTime.now());

                        FarmingInfo savedInfo = farmingInfoRepository.save(farmingInfo);

                        // 创建一条种植活动记录
                        FarmingActivity activity = new FarmingActivity();
                        activity.setUser(user);
                        activity.setType("product");
                        activity.setContent("添加了新的种植信息: " + farmingInfo.getName());

                        farmingActivityRepository.save(activity);

                        return ResponseEntity.ok(savedInfo);
                    })
                    .orElse(ResponseEntity.badRequest().body((FarmingInfo) createErrorMap("User not found with id: " + userId)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("保存种植信息失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取种植信息
     * @param id 种植信息ID
     * @return 种植信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getFarmingInfoById(@PathVariable Long id) {
        return farmingInfoRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 根据用户ID获取种植信息列表
     * @param userId 用户ID
     * @return 种植信息列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getFarmingInfoByUserId(@PathVariable Long userId) {
        try {
            List<FarmingInfo> infoList = farmingInfoRepository.findByUserId(userId);
            return ResponseEntity.ok(infoList);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("获取种植信息列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据批次ID获取种植信息
     * @param batchId 批次ID
     * @return 种植信息
     */
    @GetMapping("/batch/{batchId}")
    public ResponseEntity<?> getFarmingInfoByBatchId(@PathVariable String batchId) {
        return farmingInfoRepository.findByBatchId(batchId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 更新种植信息
     * @param id 种植信息ID
     * @param farmingInfo 种植信息
     * @return 更新后的种植信息
     */
    @PutMapping("/{id}")
    @Transactional
    public ResponseEntity<?> updateFarmingInfo(
            @PathVariable Long id,
            @RequestBody FarmingInfo farmingInfo) {
        try {
            return farmingInfoRepository.findById(id)
                    .map(existingInfo -> {
                        farmingInfo.setId(id);
                        // 保留原始的创建时间和用户信息
                        farmingInfo.setCreatedAt(existingInfo.getCreatedAt());
                        farmingInfo.setUser(existingInfo.getUser());
                        farmingInfo.setUpdatedAt(LocalDateTime.now());

                        FarmingInfo updatedInfo = farmingInfoRepository.save(farmingInfo);

                        // 创建一条更新活动记录
                        FarmingActivity activity = new FarmingActivity();
                        activity.setUser(existingInfo.getUser());
                        activity.setType("product");
                        activity.setContent("更新了种植信息: " + farmingInfo.getName());

                        farmingActivityRepository.save(activity);

                        return ResponseEntity.ok(updatedInfo);
                    })
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("更新种植信息失败: " + e.getMessage()));
        }
    }

    /**
     * 删除种植信息
     * @param id 种植信息ID
     * @return 响应
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ResponseEntity<?> deleteFarmingInfo(@PathVariable Long id) {
        try {
            return farmingInfoRepository.findById(id)
                    .map(farmingInfo -> {
                        // 记录删除活动
                        FarmingActivity activity = new FarmingActivity();
                        activity.setUser(farmingInfo.getUser());
                        activity.setType("product");
                        activity.setContent("删除了种植信息: " + farmingInfo.getName());
                        farmingActivityRepository.save(activity);

                        farmingInfoRepository.deleteById(id);
                        return ResponseEntity.ok().build();
                    })
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("删除种植信息失败: " + e.getMessage()));
        }
    }

    /**
     * 创建错误响应Map
     * @param errorMessage 错误信息
     * @return 错误响应Map
     */
    private Map<String, Object> createErrorMap(String errorMessage) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("error", errorMessage);
        return errorMap;
    }
}
